/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.controller
 * 创建时间：2020年04月11日 16时42分
 **/
package com.zhongwang.mms.module.purchase.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zhongwang.mms.base.BaseService;
import com.zhongwang.mms.common.ImportCallBack;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.basic.dao.BoardDao;
import com.zhongwang.mms.module.basic.dao.TDeptDao;
import com.zhongwang.mms.module.basic.dao.TProjectDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.purchase.dao.PurChangeDao;
import com.zhongwang.mms.module.purchase.dao.PurInvProDao;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.dao.PurTProjectDao;
import com.zhongwang.mms.module.purchase.excelListener.PInvProListener;
import com.zhongwang.mms.module.purchase.model.*;
import com.zhongwang.mms.module.system.util.GetDateTimeService;
import com.zhongwang.mms.util.FileUtils;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.zhongwang.mms.config.timingtask.StatisticalTimingTask.getVWProjectByCode;

/**
 * @ClassName： PurChangeController
 * @Description： 串料控制层
 * @Author： 徐一贺
 * @Date： 2020/4/11 16:42
 * @Version： V1.0
 **/
@Log4j2
@Service
public class PurInvProService extends BaseService {
    @Value("${user.upload.path}")
    private String uploadPath;
    @Autowired
    private PurInvProDao purInvProDao;
    @Autowired
    private PurPInventoryDao purPInventoryDao;
    @Autowired
    private GetDateTimeService getDateTimeService;
    @Autowired
    private PurTProjectDao purTProjectDao;
    @Autowired
    private TDeptDao tDeptDao;
    @Autowired
    private BoardDao boardDao;
    @Autowired
    private BaseService baseService;
    @Autowired
    private TWarehouseInfoDao tWarehouseInfoDao;
    @Autowired
    private TProjectDao tProjectDao;
    @Autowired
    private PurChangeDao purChangeDao;
    @Autowired
    private BoardService boardService;

    /**
     * @FunctionName: findChangePlanList
     * @Description: 获取串料计划列表
     * @Author: 徐一贺
     * @CreateDate: 2020/4/15 19:39
     * @Phone: 18241927380
     * @Param: [queryModel] 检索参数
     * @Return: [List<ChangeModel>] 串料计划列表
     * @Version: 1.0.0
     */
    public List<ChangeModel> findChangePlanList(ChangeModel queryModel) {
        return purInvProDao.findChangePlanList(queryModel);
    }


    /**
     * @FunctionName: saveChangeOrder
     * @Description: 保存库存划项目标记
     * @Author: 徐一贺
     * @CreateDate: 2020/4/20 11:17
     * @Phone: 18241927380
     * @Param: [param] 参数
     * @Return: 结果
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveInvPro(PInventoryProjectMarkModel param) {
        JsonResult jsonResult = new JsonResult();
        try {
            //根据主键获取库存信息
            PInventory ceoUsePInventory = purInvProDao.getInventoryPrimaryKey(param.getIpmBeforeItyId());
            param.setIpmItyType("p");
            param.setIpmProposerId(ShiroUtils.getUser().getId());
            param.setIpmDate(new Date());
            param.setIpmMatCode(ceoUsePInventory.getItySapCode());
            param.setIpmAppStatus(1);
            if (ceoUsePInventory.getItyAvaNum() < param.getIpmNum()) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("可用数量不足！");
                return jsonResult;
            }
//            if(purPInventoryDao.getTCostByCode(param.getIpmInProjectCode().trim())!=null){
//                jsonResult.setType(JsonResult.ResultType.ERROR);
//                jsonResult.setMsg("【新项目编号】不可以是成本中心项目号！");
//                return jsonResult;
//            }
            //更改库存可用数量
            ceoUsePInventory.setItyAvaNum(ceoUsePInventory.getItyAvaNum() - param.getIpmNum());
            purPInventoryDao.updateItyAvaNumByPrimary(ceoUsePInventory);
            param.setIpmMatDesc(StringUtils.replaceNbspToSpace(param.getIpmMatDesc()));
            param.setIpmInProjectName(StringUtils.replaceNbspToSpace(param.getIpmInProjectName()));
            param.setIpmInProjectCode(StringUtils.replaceNbspToSpace(param.getIpmInProjectCode()));
            param.setIpmMatCode(StringUtils.replaceNbspToSpace(param.getIpmMatCode()));
            param.setIpmRemark(StringUtils.replaceNbspToSpace(param.getIpmRemark()));
            purInvProDao.insertSelective(param);
            logService.saveLog("【外购件】创建库存划项目标记", "被划项目的库存物料描述：" + ceoUsePInventory.getItyMatDesc());
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("创建库存划项目标记成功！");
            return jsonResult;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("创建库存划项目标记失败！");
            return jsonResult;
        }
    }


    /**
     * @FunctionName: generateCCOrderCode
     * @Description: 获取串料单编码
     * @Author: 徐一贺
     * @CreateDate: 2020/4/16 13:06
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Version:
     */
    private String generateCCOrderCode() {
        String newGeneratePRKOrderCode = "";
        //获取最后编码
        String lastCCOrderCode = purInvProDao.findLastCCOrderCode();
        if (null == lastCCOrderCode) {
            lastCCOrderCode = "";
        }
        //获取当前时间简码
        String datetimeCode = new SimpleDateFormat("yyMMdd").format(new Date());
        Integer sn = 0;
        if (lastCCOrderCode.length() > 0) {
            //获取外购件库最新最后的入库单号
            sn = Integer.parseInt(lastCCOrderCode.substring(9));
        }

        if (lastCCOrderCode.length() == 0) {
            newGeneratePRKOrderCode = "CC" + new SimpleDateFormat("yyMMdd").format(new Date()) + "000001";
        } else if (!lastCCOrderCode.substring(3, 9).equals(datetimeCode)) {
            newGeneratePRKOrderCode = "CC" + new SimpleDateFormat("yyMMdd").format(new Date()) + "000001";
        } else {
            newGeneratePRKOrderCode = "CC" + new SimpleDateFormat("yyMMdd").format(new Date()) + String.format("%06d", (sn + 1));
        }
        return newGeneratePRKOrderCode;
    }


//    /**
//     * @FunctionName: getPInventory
//     * @Description: 根据需求的库存信息主键查找库存信息
//     * @Author: 徐一贺
//     * @CreateDate: 2020/4/18 10:09
//     * @Phone: 18241927380
//     * @Param: [ceoUseItyId] 需求的库存信息主键
//     * @Return: [pInventory] 查找到了库存信息
//     * @Version: 1.0.0
//     */
//    public PChangeOrder getPInventory(Integer ceoUseItyId) {
//        PInventory pInventory = purInvProDao.findInventoryByParam(ceoUseItyId);
//        TProject tProject = purInvProDao.getTProjectByProCode(pInventory.getItyProCode());
//        PChangeOrder pChangeOrder = new PChangeOrder();
//        pChangeOrder.setCeoUseItyId(pInventory.getItyId());
//        if (null != tProject) {
//            pChangeOrder.setCeoUseStatus(tProject.getProProductionStatus());
//        }
//        pChangeOrder.setCeoUseProCode(pInventory.getItyProCode());
//        pChangeOrder.setCeoUseProName(pInventory.getItyProName());
//        pChangeOrder.setCeoUseMatName(pInventory.getItyMatDesc());
//        pChangeOrder.setCeoUseMatCode(pInventory.getItySapCode());
//
//        pChangeOrder.setCeoUseNum(pInventory.getItyAvaNum());
//        pChangeOrder.setCeoUseUnit(pInventory.getItyNumUnit());
//        pChangeOrder.setCeoNeedUnit(pInventory.getItyNumUnit());
//        pChangeOrder.setCeoUseWhiId(pInventory.getItyWhiId());
//        pChangeOrder.setCeoUsePosition(pInventory.getItyPosition());
//
//
//        return pChangeOrder;
//    }

    /**
     * @FunctionName: findVWProjectByLikeCode
     * @Description: 根据项目号模糊查询获取看板系统项目信息与本地系统项目状态列表
     * @Author: 徐一贺
     * @CreateDate: 2020/4/18 12:52
     * @Phone: 18241927380
     * @Param: [param] 包含项目号实体类
     * @Return: [List<VWProject>] 项目看板系统列表信息
     * @Version: 1.0.0
     */
    public List<VWProject> findVWProjectByLikeCode(VWProject param) {
        return purInvProDao.findVWProjectByLikeCode(param);
    }

    /**
     * @FunctionName: codeExist
     * @Description: bootstrapValidate验证：验证项目号是否存在
     * @JavaScriptDemo： notEmpty: {message: '请输入需求项目编号'},
     * threshold: 6, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
     * remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
     * url: 'purchase/change/codeExist',//验证地址
     * message: '用户已存在',//提示消息
     * delay: 100,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
     * type: 'POST'//请求方式
     * /**自定义提交数据，默认值提交当前input value
     * *  data: function(validator) {
     * return {
     * password: $('[name="passwordNameAttributeInYourForm"]').val(),
     * whatever: $('[name="whateverNameAttributeInYourForm"]').val()
     * };
     * }
     * @Author: 徐一贺
     * @CreateDate: 2020/4/18 13:24
     * @Phone: 18241927380
     * @Param: [param] 项目号
     * @Return: java.lang.Boolean
     * @Version: 1.0.0
     */
    public Boolean codeExist(VWProject param) {
        VWProject vwProject = getVWProjectByCode(param.getCode());
        return vwProject != null;
    }

    /**
     * @FunctionName: proInfoExist
     * @Description: 根据项目号查询本系统项目是否存在
     * @Author: 徐一贺
     * @CreateDate: 2020/4/20 13:31
     * @Phone: 18241927380
     * @Param: [param] 项目号
     * @Return: [Boolean] 返回结果
     * @Version: 1.0.0
     */
    public Boolean proInfoExist(VWProject param) {
        TProject tProject = purInvProDao.getTProjectByProCode(param.getCode());
        return tProject != null;
    }

    /**
     * @FunctionName: findChangeOrderListByQuery
     * @Description: 根据条件号查询库存划项目标记执行表列表数据
     * @Author: 徐一贺
     * @CreateDate: 2020/4/20 14:47
     * @Phone: 18241927380
     * @Param: [queryModel] 查询条件
     * @Return: [List<PChangeOrderModel>] 串料单标记列表
     * @Version: 1.0.0
     */
    public List<PInventoryProjectMarkModel> findPInventoryProjectMarkListByQuery(PInventoryProjectMarkQueryModel queryModel) {
        if (queryModel.getEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(queryModel.getEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            queryModel.setEndDate(cal.getTime());
        }
        if (queryModel.getEndRemoveDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(queryModel.getEndRemoveDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            queryModel.setEndRemoveDate(cal.getTime());
        }
        if (queryModel.getEndSubmitDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(queryModel.getEndSubmitDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            queryModel.setEndSubmitDate(cal.getTime());
        }
        return purInvProDao.findPInventoryProjectMarkListByQuery(queryModel);
    }

    /**
     * @FunctionName: findChangeOrderExecListByQuery
     * @Description: 获取库存划项目执行列表
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 19:43
     * @Phone: 18241927380
     * @Param: [queryModel] 检索参数
     * @Return: [List<ChangeModel>] 串料执行列表
     * @Version: 1.0.0
     */
    public List<PInventoryProjectMarkModel> findPInventoryProjectMarkExecListByQuery(PInventoryProjectMarkQueryModel queryModel) {
        if (queryModel.getEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(queryModel.getEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            queryModel.setEndDate(cal.getTime());
        }
        if (queryModel.getExecEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(queryModel.getExecEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            queryModel.setExecEndDate(cal.getTime());
        }
        if (queryModel.getExecEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(queryModel.getExecEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            queryModel.setExecEndDate(cal.getTime());
        }

        return purInvProDao.findPInventoryProjectMarkExecListByQuery(queryModel);
    }

    public void exportExcel(HttpServletResponse response, PInventoryProjectMarkQueryModel param) {
        if (param.getEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(param.getEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            param.setEndDate(cal.getTime());
        }
        if (param.getExecEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(param.getExecEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            param.setExecEndDate(cal.getTime());
        }
//        purInvProDao.findPInventoryProjectMarkExecListByQuery(param);
        List<PInventoryProjectMarkModel> list = new ArrayList<>();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String path = uploadPath + user.getAccount() + "/";
        Subject userSubject = ShiroUtils.getSubject();
        //1.创建临时内存表名
        String tempTableName = "##" + ShiroUtils.getUser().getAccount() + (UUID.randomUUID().toString().replace("-", ""));
        param.setTempTableName(tempTableName);
        //2.查询出数据导入到临时表
        purInvProDao.createPInventoryProjectMarkExecListTempTable(param);
        //3.查询临时内存表数据导出
        Integer dataCount = purInvProDao.getTempTableDataCount(param);
        int step = 5000;
        FileUtils.mkdirs(path);
        // 方法1 如果写到同一个sheet
        path = path + "外购件库存划项目申请列表.xlsx";
        ExcelWriter excelWriter = null;
        try {
            // 这里 需要指定写用哪个class去写
            excelWriter = EasyExcel.write(path, PInventoryProjectMarkModel.class).build();
            // 这里注意 如果同一个sheet只要创建一次
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
            for (int topCount = 5000, notHaveTopCount = 0; notHaveTopCount < dataCount; notHaveTopCount += step) {
                param.setTopCount(topCount);
                param.setNotHaveTopCount(notHaveTopCount);
                list = purInvProDao.selectPInventoryProjectMarkExecListTempTableByParam(param);
                if (list != null) {
                    excelWriter.write(list, writeSheet);
                }
            }
            //4.删除临时内存表
            purInvProDao.dropPInventoryProjectMarkExecListTempTable(tempTableName);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        //5.下载
        FileUtils.downloadFile(path, response);
    }

    /**
     * @FunctionName: findDeptList
     * @Description: 获取单位列表
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 10:13
     * @Phone: 18241927380
     * @Param:
     * @Return: [List<TDept>] 单位列表
     * @Version: 1.0.0
     */
    public List<TDept> findDeptList() {
        return tDeptDao.selectByExample(null);
    }

    /**
     * @FunctionName: submitAppy
     * @Description: 提交
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 12:39
     * @Phone: 18241927380
     * @Param: [param]
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean submitAppy(PInventoryProjectMarkModel param) {
        try {
            String[] ipmIdArray = param.getIpmIds().split(",");
            Date currentTime = new Date();
            for (String ipmIdStr : ipmIdArray) {
                PInventoryProjectMarkModel logModel = purInvProDao.getPInventoryProjectMarkModelAndItyAvaNum(Integer.parseInt(ipmIdStr));
                if (logModel.getIpmAppStatus().equals(1) || logModel.getIpmAppStatus().equals(2)) {
                    logModel.setIpmAppStatus(3);
                    logModel.setIpmSubmitDate(currentTime);
                    purInvProDao.updatePChangeOrderCeoAppyStatusByCeoId(logModel);
                    logService.saveLog("【外购件】提交库存划项目标记", "提交的划项目的库存物料描述：" + logModel.getItyMatDesc());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * @FunctionName: execApply
     * @Description: 执行
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 20:12
     * @Phone: 18241927380
     * @Param: [param] 执行参数
     * @Return: [boolean] 执行结果
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult execApply(PInventoryProjectMarkModel param) {
        JsonResult jsonResult = new JsonResult();
        List<String> errorList = new ArrayList<>();
        //更改库存
        //首先获取串料实体类
        List<PInventoryProjectMarkModel> PInventoryProjectMarkModelList = purInvProDao.findPInventoryProjectMarkByCeoId(param.getIpmIds());
        for (int i = 0; i < PInventoryProjectMarkModelList.size(); i++) {
            PInventoryProjectMarkModel pInventoryProjectMarkModel = PInventoryProjectMarkModelList.get(i);
            PInventory ceoUsePInventory = purInvProDao.getInventoryPrimaryKey(pInventoryProjectMarkModel.getIpmBeforeItyId());
            if (pInventoryProjectMarkModel.getIpmAppStatus() == 3) {
                if (pInventoryProjectMarkModel.getIpmNum() > ceoUsePInventory.getItyNum()) {
                    errorList.add("物料名称为：" + ceoUsePInventory.getItyMatDesc() + "的在库数量数量不足，无法执行！");
                }
            } else {
                errorList.add("物料名称为：" + ceoUsePInventory.getItyMatDesc() + "的申请已经驳回或执行，无法再次执行！");
            }
        }
        if (errorList.size() > 0) {
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg(errorList.toString());
            return jsonResult;
        }
        for (int i = 0; i < PInventoryProjectMarkModelList.size(); i++) {
            PInventoryProjectMarkModel pInventoryProjectMarkModel = PInventoryProjectMarkModelList.get(i);
            if (pInventoryProjectMarkModel.getIpmAppStatus().equals(3)) {
                PInventory ceoUsePInventory = purInvProDao.getInventoryPrimaryKey(pInventoryProjectMarkModel.getIpmBeforeItyId());
                //插入串过来库存的数据
                if (null != param.getItyPosition() && !param.getItyPosition().equals("")) {
                    ceoUsePInventory.setItyPosition(param.getItyPosition());
                }
                ceoUsePInventory.setItyProCode(pInventoryProjectMarkModel.getIpmInProjectCode());
                ceoUsePInventory.setItyProName(pInventoryProjectMarkModel.getIpmInProjectName());
                ceoUsePInventory.setItyNum(pInventoryProjectMarkModel.getIpmNum());
                ceoUsePInventory.setItyAvaNum(pInventoryProjectMarkModel.getIpmNum());
                if (purPInventoryDao.getTCostByCode(pInventoryProjectMarkModel.getIpmInProjectCode().trim()) != null) {
                    ceoUsePInventory.setItyStockType(1);
                } else {
                    ceoUsePInventory.setItyStockType(2);
                }
                purPInventoryDao.insert(ceoUsePInventory);
                ceoUsePInventory.setItyInvProFlag(1);
                purPInventoryDao.updateItyInvProFlagByPrimaryKey(ceoUsePInventory);
                //反写使用的库存信息到串料数据中,等待提报计划指定。
                pInventoryProjectMarkModel.setIpmAfterItyId(ceoUsePInventory.getItyId());
                pInventoryProjectMarkModel.setIpmAppStatus(4);
                pInventoryProjectMarkModel.setIpmExecutorId(ShiroUtils.getUser().getId());
                pInventoryProjectMarkModel.setIpmExecDate(new Date());
                pInventoryProjectMarkModel.setIpmPrice(ceoUsePInventory.getItyPrice());
                purInvProDao.updateSelective(pInventoryProjectMarkModel);
                //获取原库存数据并更改其值为,库存数量为库存声来减去可用数量，可用数量清零。
                ceoUsePInventory = purInvProDao.getInventoryPrimaryKey(pInventoryProjectMarkModel.getIpmBeforeItyId());
                ceoUsePInventory.setItyNum(ceoUsePInventory.getItyNum() - pInventoryProjectMarkModel.getIpmNum());
                if (ceoUsePInventory.getItyInvProFlag() == null || ceoUsePInventory.getItyInvProFlag().equals(0)) {
                    ceoUsePInventory.setItyInvProFlag(2);
                    purPInventoryDao.updateItyInvProFlagByPrimaryKey(ceoUsePInventory);
                } else if (ceoUsePInventory.getItyInvProFlag().equals(1)) {
                    ceoUsePInventory.setItyInvProFlag(3);
                    purPInventoryDao.updateItyInvProFlagByPrimaryKey(ceoUsePInventory);
                }
                purPInventoryDao.updateNumByPrimaryKey(ceoUsePInventory);
                logService.saveLog("【外购件】执行库存划项目标记", "执行的划项目的库存物料描述：" + ceoUsePInventory.getItyMatDesc());
            }
        }
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setMsg("执行成功！");
        return jsonResult;
    }

    /**
     * @FunctionName: revokeAppy
     * @Description: 撤销
     * @Author: 徐一贺
     * @CreateDate: 2020/4/22 9:20
     * @Phone: 18241927380
     * @Param: [param] 撤销参数
     * @Return: [boolean] 侧小结果
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean revokeAppy(PInventoryProjectMarkModel param) {
        try {
            List<PInventoryProjectMarkModel> PInventoryProjectMarkModelList = purInvProDao.findPInventoryProjectMarkByCeoId(param.getIpmIds());
            //检测所有申请是否已经出库或被串料，如何验证出库，即串料之后的新库存数据可用数量或者库存数量小于串料数量则不可撤销
            for (PInventoryProjectMarkModel pInventoryProjectMarkModel : PInventoryProjectMarkModelList) {
                //获取因项目划库存新生成的数据
                PInventory ceoNeedPInventory = purInvProDao.getInventoryPrimaryKey(pInventoryProjectMarkModel.getIpmAfterItyId());
//                //如果被执行项目化库存则不可撤销
//                if (ceoNeedPInventory.getItyStockType().equals(1)) {
//                    return false;
//                }
                //如果发现因出库、标记造成的库存数量或可用数量无法撤销则返回假
                if (ceoNeedPInventory.getItyNum() < pInventoryProjectMarkModel.getIpmNum() ||
                        ceoNeedPInventory.getItyAvaNum() < pInventoryProjectMarkModel.getIpmNum()) {
                    return false;
                }
            }
            //更改库存
            //首先获取库存划项目实体类
            for (int i = 0; i < PInventoryProjectMarkModelList.size(); i++) {
                PInventoryProjectMarkModel pInventoryProjectMarkModel = PInventoryProjectMarkModelList.get(i);
                if (pInventoryProjectMarkModel.getIpmAppStatus().equals(4)) {
                    //如果被指定计划,则清除指定计划的标记状态为0
                    if (null != pInventoryProjectMarkModel.getIpmRppId()) {
                        BReportPlan bReportPlan = purInvProDao.getBReportPlanPrimaryKey(pInventoryProjectMarkModel.getIpmRppId());
                        bReportPlan.setRppIsFlag(0);
                        purInvProDao.uppdateBReportPlanRppIsFlagByPrimaryKey(bReportPlan);
                    }
                    //获取被划项目的库存，回写增加被串料的数量
                    PInventory ceoUsePInventory = purInvProDao.getInventoryPrimaryKey(pInventoryProjectMarkModel.getIpmBeforeItyId());
                    ceoUsePInventory.setItyNum(ceoUsePInventory.getItyNum() + pInventoryProjectMarkModel.getIpmNum());
//                ceoUsePInventory.setItyAvaNum(ceoUsePInventory.getItyAvaNum() + pInventoryProjectMarkModel.getIpmNum());
                    purPInventoryDao.updateNumByPrimaryKey(ceoUsePInventory);
                    //获取库存划项目生成的库存，清零0库存
                    PInventory ceoNeedPInventory = purInvProDao.getInventoryPrimaryKey(pInventoryProjectMarkModel.getIpmAfterItyId());
                    ceoNeedPInventory.setItyNum(0d);
                    ceoNeedPInventory.setItyAvaNum(0d);
                    purPInventoryDao.updateNumByPrimaryKey(ceoNeedPInventory);
                    ceoNeedPInventory.setItyInvProFlag(0);
                    purPInventoryDao.updateItyInvProFlagByPrimaryKey(ceoNeedPInventory);
                    //驳回此串料单：清空标记计划ID为0，申请状态为作废。
                    PInventoryProjectMarkModel modelReject = new PInventoryProjectMarkModel();
                    modelReject.setIpmId(pInventoryProjectMarkModel.getIpmId());
                    modelReject.setIpmRppId(null);
                    modelReject.setIpmAfterItyId(null);
                    modelReject.setIpmAppStatus(3);
                    modelReject.setIpmExecutorId(null);
                    modelReject.setIpmExecDate(null);
                    purInvProDao.updateReject(modelReject);
                    //获取被执行过的库存划项目次数
                    Integer changeCount = purInvProDao.getInvProCountByItyId(ceoUsePInventory.getItyId());
                    if (ceoUsePInventory.getItyInvProFlag() == 3 && changeCount == 0) {
                        ceoUsePInventory.setItyInvProFlag(1);
                        purPInventoryDao.updateItyInvProFlagByPrimaryKey(ceoUsePInventory);
                    } else if (changeCount == 0) {
                        ceoUsePInventory.setItyInvProFlag(0);
                        purPInventoryDao.updateItyInvProFlagByPrimaryKey(ceoUsePInventory);
                    }
                    logService.saveLog("【外购件】撤销库存划项目标记", "撤销的划项目的库存物料描述：" + ceoUsePInventory.getItyMatDesc());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * @FunctionName: removeAppy
     * @Description: 删除
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 12:39
     * @Phone: 18241927380
     * @Param: [param]
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean removeAppy(PInventoryProjectMarkModel param) {
        try {
            //获取申请列表，往回标记库存
            List<PInventoryProjectMarkModel> PInventoryProjectMarkModelList = purInvProDao.findPInventoryProjectMarkByCeoId(param.getIpmIds());
            for (int i = 0; i < PInventoryProjectMarkModelList.size(); i++) {
                if (PInventoryProjectMarkModelList.get(i).getIpmDataStatus() == null && (PInventoryProjectMarkModelList.get(i).getIpmAppStatus().equals(1) || PInventoryProjectMarkModelList.get(i).getIpmAppStatus().equals(2))) {
                    PInventory ceoUsePInventory = purInvProDao.getInventoryPrimaryKey(PInventoryProjectMarkModelList.get(i).getIpmBeforeItyId());
                    ceoUsePInventory.setItyAvaNum(ceoUsePInventory.getItyAvaNum() + PInventoryProjectMarkModelList.get(i).getIpmNum());
                    if (ceoUsePInventory.getItyAvaNum() <= ceoUsePInventory.getItyNum()) {
                        purPInventoryDao.updateItyAvaNumByPrimary(ceoUsePInventory);
                    }
                    logService.saveLog("【外购件】删除库存划项目标记", "删除的划项目的库存物料描述：" + ceoUsePInventory.getItyMatDesc());
                    PInventoryProjectMarkModelList.get(i).setIpmRemoveDate(getDateTimeService.getSysDateTime());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    PInventoryProjectMarkModelList.get(i).setIpmRemoveDateStr(sdf.format(getDateTimeService.getSysDateTime()));
                    PInventoryProjectMarkModelList.get(i).setIpmRemoveUserId(ShiroUtils.getUserId());
                    purInvProDao.deleteByPrimaryKey(PInventoryProjectMarkModelList.get(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * @FunctionName: invalid
     * @Description: 驳回
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 12:39
     * @Phone: 18241927380
     * @Param: [param]
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean invalid(PInventoryProjectMarkModel param) {
        try {
            List<PInventoryProjectMarkModel> list = purInvProDao.findPInventoryProjectMarkByCeoId(param.getIpmIds());
            for (PInventoryProjectMarkModel pInventoryProjectMarkModel : list) {
                if (pInventoryProjectMarkModel.getIpmAppStatus() == 3) {
                    PInventoryModel pInventoryModel = purPInventoryDao.getInventoryByPrimaryKey(pInventoryProjectMarkModel.getIpmBeforeItyId());
                    logService.saveLog("【外购件】驳回库存划项目标记", "驳回的库存划项目的库存物料描述：" + pInventoryModel.getItyMatDesc());
                    pInventoryProjectMarkModel.setIpmAppStatus(2);
                    pInventoryProjectMarkModel.setIpmRejectReason(param.getIpmRejectReason().replace("&nbsp;", " "));
                    purInvProDao.updatePChangeOrderCeoApplyStatusByCeoId(pInventoryProjectMarkModel);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * @FunctionName: inventoryList
     * @Description: 获取库存在库库存列表
     * @Author: 徐一贺
     * @CreateDate: 2020/4/23 9:15
     * @Phone: 18241927380
     * @Param: [param] 查询参数
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    public List<PInventoryModel> findInventoryList(PInventoryModel param) {
        param.setSort(StringUtils.convertFieldToColumn(param.getSort()));
        param.setItyStockType(1);
        return purPInventoryDao.findInventoryList(param);
    }

    /**
     * @FunctionName: getInfo
     * @Description: 根据主键获取库存划项目实体
     * @Author: 徐一贺
     * @CreateDate: 2020/5/14 13:24
     * @Phone: 18241927380
     * @Param: [param]
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    public PInventoryProjectMarkModel getInfo(PInventoryProjectMarkModel param) {
        return purInvProDao.getPInventoryProjectMarkModelAndItyAvaNum(param.getIpmId());
    }

    /**
     * @FunctionName: saveEdit
     * @Description: 保存修改
     * @Author: 徐一贺
     * @CreateDate: 2020/5/14 13:48
     * @Phone: 18241927380
     * @Param: [param]
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveEdit(PInventoryProjectMarkModel param) {
        JsonResult jsonResult = new JsonResult();
        try {
            PInventory pInventory = purInvProDao.getInventoryPrimaryKey(param.getIpmBeforeItyId());
            PInventoryProjectMarkModel before = purInvProDao.getPInventoryProjectMarkModelAndItyAvaNum(param.getIpmId());
            if ((pInventory.getItyAvaNum() + before.getIpmNum()) < param.getIpmNum()) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("标记数量大于可用数量！");
            } else {
                pInventory.setItyAvaNum(pInventory.getItyAvaNum() - (param.getIpmNum() - before.getIpmNum()));
                purPInventoryDao.updateItyAvaNumByPrimary(pInventory);
                PInventoryProjectMarkModel changeModel = new PInventoryProjectMarkModel();
                changeModel.setIpmId(param.getIpmId());
                changeModel.setIpmInProjectCode(param.getIpmInProjectCode());
                changeModel.setIpmInProjectName(param.getIpmInProjectName());
                changeModel.setIpmNum(param.getIpmNum());
                changeModel.setIpmRemark(param.getIpmRemark());
                changeModel.setIpmAppStatus(1);
                changeModel.setIpmStandardNo(param.getIpmStandardNo());
                changeModel.setIpmMatDesc(param.getIpmMatDesc());
                purInvProDao.updatePInventoryProjectMarkModelByPrimaryKeySelective(changeModel);
                logService.saveLog("【外购件】修改库存划项目标记", "修改的库存划项目标记的库存物料描述：" + pInventory.getItyMatDesc());
            }
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("保存修改成功！");
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("保存修改失败！");
        }
        return jsonResult;
    }

    /**
     * @FunctionName: importExcel
     * @Description: 导入批量库存划项目标识Excel
     * @DesignIdea: 请填写设计思想
     * @Author: 徐一贺
     * @CreateDate: 2020/6/15 14:49
     * @Phone: 18241927380
     * @Param: [file]
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Throw:
     * @Version: v 1.0.0
     */
    public JsonResult importExcel(MultipartFile file) {
        JsonResult result = new JsonResult();
        try {
            FileUtils.importExcel(file, PChangeOrderExcelModel.class, new PInvProListener(purInvProDao, boardDao, new ImportCallBack() {
                @Override
                public void onSuccess() {
                    result.setType(JsonResult.ResultType.SUCCESS);
                    result.setMsg("批量导入成功！");
                }

                @Override
                public void onWarning(List list) {
                    result.setType(JsonResult.ResultType.ERROR);
                    for (int i = 0; i < list.size(); i++) {
                        purChangeDao.insertErrorLog((PChangeImportExportLogModel) list.get(i));
                    }
                }
            }, logService, baseService, purPInventoryDao, tWarehouseInfoDao, tProjectDao, purChangeDao, boardService));
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            result.setType(JsonResult.ResultType.ERROR);
            result.setMsg("批量导入失败！");
        }
        return result;
    }

    /**
     * @FunctionName: getPInventory
     * @Description: 根据主键过去库存实体
     * @DesignIdea: 根据主键过去库存实体
     * @Author: 徐一贺
     * @CreateDate: 2020/6/22 14:09
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Throw:
     * @Version: v 1.0.0
     */
    public PInventoryModel getPInventory(PInventoryModel param) {
        return purPInventoryDao.getInventoryByPrimaryKey(param.getItyId());
    }
}